package com.ruoyi.system.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 归还单主Controller
 *
 * @author ruoyi
 * @date 2024-10-31
 */
@RestController
@RequestMapping("/system/HmzReturnMaster")
public class HmzReturnMasterController extends BaseController
{
    @Autowired
    private IHmzReturnMasterService hmzReturnMasterService;
    //    员工操作类
    @Autowired
    private IHmzEmployeeInfoService hmzEmployeeInfoService;
    //    托盘操作类
    @Autowired
    private IHmzItemService hmzItemService;
    //    归还单子表操作类
    @Autowired
    private IHmzReturnDetailService hmzReturnDetailService;
    //    领用单子表操作类
    @Autowired
    private IHmzBorrowDetailService hmzBorrowDetailService;
    //    领用主表操作类
    @Autowired
    private IHmzBorrowMasterService hmzBorrowMasterService;
    /**
     * 查询归还单主列表
     */
    @PreAuthorize("@ss.hasPermi('system:HmzReturnMaster:list')")
    @GetMapping("/list")
    public TableDataInfo list(HmzReturnMaster hmzReturnMaster)
    {
        //        如果条件查询中有员工名称，则先取出员工id
        System.out.printf("员工名称="+hmzReturnMaster.getName());
        if (hmzReturnMaster.getName()!=null) {
            HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoByName(hmzReturnMaster.getName());
            if(hmzEmployeeInfo ==null){
                return getDataTable(Collections.emptyList());
            }
            Long id =  hmzEmployeeInfo.getId();
            hmzReturnMaster.setEmployeeId(id);
            System.out.printf("员工id="+id);
        }
        startPage();
        List<HmzReturnMaster> list = hmzReturnMasterService.selectHmzReturnMasterList(hmzReturnMaster);
//            获取员工id进行遍历查询,获取到员工详情
        for (HmzReturnMaster item:list )
        {
            HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoById(item.getEmployeeId());
//           给归还单主表实体类的临时字段赋值(名称和rfid编号)
            item.setName(hmzEmployeeInfo.getName());
            item.setRfidCode(hmzEmployeeInfo.getRfidCode());

        }
        System.out.println("item = " + list);
        return getDataTable(list);
    }

    /**
     * 导出归还单主列表
     */
    @PreAuthorize("@ss.hasPermi('system:HmzReturnMaster:export')")
    @Log(title = "归还单主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HmzReturnMaster hmzReturnMaster)
    {
        List<HmzReturnMaster> list = hmzReturnMasterService.selectHmzReturnMasterList(hmzReturnMaster);
        ExcelUtil<HmzReturnMaster> util = new ExcelUtil<HmzReturnMaster>(HmzReturnMaster.class);
        util.exportExcel(response, list, "归还单主数据");
    }

    /**
     * 获取归还单主详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:HmzReturnMaster:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        //        获取领用单详情
        HmzReturnMaster hmzReturnMaster = hmzReturnMasterService.selectHmzReturnMasterById(id);
        //        获取员工详情
        HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoById(hmzReturnMaster.getEmployeeId());
//        给详情赋值员工的rfidcode和名称
        hmzReturnMaster.setName(hmzEmployeeInfo.getName());
        hmzReturnMaster.setRfidCode(hmzEmployeeInfo.getRfidCode());
        return success(hmzReturnMaster);
    }

    /**
     * 新增归还单主
     */
    @PreAuthorize("@ss.hasPermi('system:HmzReturnMaster:add')")
    @Log(title = "归还单主", businessType = BusinessType.INSERT)
    @PostMapping
//    @Transactional
    public AjaxResult add(@RequestBody HmzReturnMaster hmzReturnMaster)
    {
        //        根据日期生成流水号 start
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Calendar calendar = Calendar.getInstance();
        String datePortion = sdf.format(calendar.getTime());
        System.out.println("生成的序列编号是: " + datePortion); // 输出序列编号
//        根据日期生成流水号 end
        hmzReturnMaster.setGhNumber(datePortion);
//        根据归还的rfid号查询对应的员工id
//        查询领用明细表，取出领用主表id
        HmzBorrowDetail hmzBorrowDetail = new HmzBorrowDetail();
        hmzBorrowDetail.setRemark("未归还".trim());
        hmzBorrowDetail.setRfidCode(hmzReturnMaster.getHmzReturnDetailList().get(0).getRfidCode());
        Long id = hmzBorrowDetailService.selectHmzBorrowDetailList(hmzBorrowDetail).get(0).getMasterId();
//          再根据领用主表id去获取对应的员工id
      Long userId = hmzBorrowMasterService.selectHmzBorrowMasterById(id).getEmployeeId();
        hmzReturnMaster.setEmployeeId(userId);
        hmzReturnMaster.setGhQuantity((long) hmzReturnMaster.getHmzReturnDetailList().size());
//        插入归还单主表，拿到主表id
        hmzReturnMasterService.insertHmzReturnMaster(hmzReturnMaster);
        Long tableId = hmzReturnMaster.getId();
        List<HmzReturnDetail> hmzReturnDetails = hmzReturnMaster.getHmzReturnDetailList();
//       检测抛出异常
        HmzItem hmzItem;

        //            更新领用单的归还数量
//            根据rfid查询领用单明细，拿到master主表id
        HmzBorrowDetail hmzBorrowDetail0 = new HmzBorrowDetail();
        hmzBorrowDetail0.setRemark("未归还".trim());
        hmzBorrowDetail0.setRfidCode(hmzReturnMaster.getHmzReturnDetailList().get(0).getRfidCode());
        List<HmzBorrowDetail> hmzBorrowDetail1 = hmzBorrowDetailService.selectHmzBorrowDetailList(hmzBorrowDetail0);
        Long masterId =  hmzBorrowDetail1.get(0).getMasterId();
        HmzBorrowMaster hmzBorrowMaster = new HmzBorrowMaster();
        hmzBorrowMaster.setId(masterId);
        HmzBorrowMaster hmzBorrowMaster1 = hmzBorrowMasterService.selectHmzBorrowMasterById(masterId);
        Long quantity = hmzBorrowMaster1.getGhQuantity() + (long) hmzReturnMaster.getHmzReturnDetailList().size();
        hmzBorrowMaster.setGhQuantity(quantity);
        hmzBorrowMasterService.updateHmzBorrowMaster(hmzBorrowMaster);

        //       遍历将主表id 和 归还明细插入归还子表
        for (HmzReturnDetail item : hmzReturnDetails) {
            //        赋值归还主表id
            item.setMasterId(tableId);
//            根据托盘rfid获取托盘id
            hmzItem = hmzItemService.selectHmzItemByRfidCode(item.getRfidCode());
            Long tuoPanId =hmzItem.getId();
            System.out.println("托盘id: " + tuoPanId);
//           赋值托盘id
            item.setItemId(tuoPanId);
//            根据rfid查询领用单详情
            HmzBorrowDetail hmzBorrowD = new HmzBorrowDetail();
            hmzBorrowD.setRemark("未归还");
            hmzBorrowD.setRfidCode(item.getRfidCode());
           List<HmzBorrowDetail> hmzBorrowDetail2 = hmzBorrowDetailService.selectHmzBorrowDetailList(hmzBorrowD);
            hmzBorrowDetail2.get(0).setRemark("已归还");
            hmzBorrowDetailService.updateHmzBorrowDetail(hmzBorrowDetail2.get(0));
//        插入数据
            hmzReturnDetailService.insertHmzReturnDetail(item);
//            更新托盘库存状态
            hmzItem.setGoodsState(0L);
            hmzItem.setEmployeeId(null);
            hmzItemService.updateHmzItem(hmzItem);
        }


        return success("操作成功");
    }

    /**
     * 修改归还单主
     */
    @PreAuthorize("@ss.hasPermi('system:HmzReturnMaster:edit')")
    @Log(title = "归还单主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HmzReturnMaster hmzReturnMaster)
    {
        return toAjax(hmzReturnMasterService.updateHmzReturnMaster(hmzReturnMaster));
    }

    /**
     * 删除归还单主
     */
    @PreAuthorize("@ss.hasPermi('system:HmzReturnMaster:remove')")
    @Log(title = "归还单主", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(hmzReturnMasterService.deleteHmzReturnMasterByIds(ids));
    }
}
